package com.example.devopsjdk11;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.util.Objects;

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@RestController
@Slf4j
public class DevopsJdk11Application {

    public static void main(String[] args) {
        SpringApplication.run(DevopsJdk11Application.class, args);
    }

    @RequestMapping("/")
    public String hello(){
        Connection connection = null;
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setUsername("root");
        driverManagerDataSource.setPassword(mysql.getPassword());
        driverManagerDataSource.setUrl(String.format("jdbc:mysql://%s:%s?useUnicode=true&useSSL=false",mysql.getHost(),mysql.getPort()));
        driverManagerDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");

        try {
            connection = DataSourceUtils.getConnection(driverManagerDataSource);
        } catch (CannotGetJdbcConnectionException e) {
            //
        }
        if (Objects.isNull(connection)){
            return "Hello Springboot";
        }
        else {
            return String.format("Connected mysql success. Host='%s', password='%s', port='%s', username='root'",
                    mysql.getHost(),
                    mysql.getPassword(),
                    mysql.getPort());
        }

    }

    private final MysqlProperties mysql;

    public DevopsJdk11Application(MysqlProperties mysql) {
        this.mysql = mysql;
    }

    @PostConstruct
    void print(){
        log.info("【mysql配置】mysql.host='{}', mysql.port= '{}', mysql.password='{}'",mysql.getHost(),mysql.getPort(), mysql.getPassword());
    }

}
